<?php
// Version
define('VERSION', '1.5.4');

// Configuration
require_once('../config/main.php');

// Startup
require_once(DIR_SYSTEM . 'startup.php');

// Application Classes
require_once(DIR_SYSTEM . 'library/user.php');

// Loader
$loader = new Loader($registry);
Registry::set('load', $loader);

// Config
$config = new Config();
Registry::set('config', $config);

// Database
$db = new MySqlAdapter(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
Registry::set('db', $db);

// Settings
$query = $db->query("SELECT * FROM " . DB_PREFIX . "setting");

foreach ($query->rows as $setting) {
    if (!$setting['serialized']) {
        $config->set($setting['key'], $setting['value']);
    } else {
        $config->set($setting['key'], unserialize($setting['value']));
    }
}

// Log
$log = new Log($config->get('config_error_filename'));
Registry::set('log', $log);

function error_handler($errno, $errstr, $errfile, $errline) {
    global $log, $config;

    switch ($errno) {
        case E_NOTICE:
        case E_USER_NOTICE:
            $error = 'Notice';
            break;
        case E_WARNING:
        case E_USER_WARNING:
            $error = 'Warning';
            break;
        case E_ERROR:
        case E_USER_ERROR:
            $error = 'Fatal Error';
            break;
        default:
            $error = 'Unknown';
            break;
    }

    if ($config->get('config_error_display')) {
        echo '<b>' . $error . '</b>: ' . $errstr . ' in <b>' . $errfile . '</b> on line <b>' . $errline . '</b>';
    }

    if ($config->get('config_error_log')) {
        $log->write('PHP ' . $error . ':  ' . $errstr . ' in ' . $errfile . ' on line ' . $errline);
    }

    return true;
}

// Error Handler
set_error_handler('error_handler');

// Request
$request = new Request();
Registry::set('request', $request);

// Response
$response = new Response();
$response->addHeader('Content-Type: text/html; charset=utf-8');
Registry::set('response', $response);

// Cache
$cache = new Cache();
Registry::set('cache', $cache);

// Session
$session = new Session();
Registry::set('session', $session);

// Document
Registry::set('document', new Document());

// User
Registry::set('user', new User($registry));

// Front Controller
$front = new Front($registry);

// Login
$front->addPreAction(new Action('common/home/login'));

// Permission
$front->addPreAction(new Action('common/home/permission'));

// Router
if (isset($request->get['route'])) {
    $action = new Action($request->get['route']);
} else {
    $action = new Action('common/home');
}

// Dispatch
$front->dispatch($action, new Action('error/not_found'));

// Output
$response->output();
?>